package cn.how2j.trend.service;

import cn.how2j.trend.pojo.IndexData;
import cn.how2j.trend.util.SpringContextUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@CacheConfig(cacheNames = "index_data")
public class IndexDataService {
    private Map<String ,List<IndexData>> indexDatas = new HashMap<>();
    @Autowired
    RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod ="third_part_not_connected")
    public List<IndexData> fresh(String code){
        IndexDataService dataService = SpringContextUtil.getBean(IndexDataService.class);
        List<IndexData> dataList = fetch_indexes_from_third_part(code);//获取数据
        indexDatas.put(code,dataList);
        System.out.println("code:"+code);
        System.out.println("indexDatas:"+indexDatas.get(code).size());
        dataService.remove(code);
        return dataService.store(code);
    }
    @CachePut(key ="'indexData-code-'+ #p0")
    public List<IndexData> store(String code) {
        System.out.println(this);
        return indexDatas.get(code);
    }

    @CacheEvict(key = "'indexData-code-'+ #p0")
    public void remove(String code) {
    }
    @Cacheable(key = "'indexData-code-'+ #p0")
    public List<IndexData> get(String code){
        return CollUtil.toList();
    }

    public List<IndexData> fetch_indexes_from_third_part (String code) {
        List<Map> temp = restTemplate.getForObject("http://127.0.0.1:8090/indexes/"+code+".json",List.class );
        return map2IndexData(temp);
    }
    //断路器方法
    public List<IndexData> third_part_not_connected(String code){
        IndexData indexData = new IndexData();
        indexData.setDate("暂无数据");
        indexData.setClosePoint((float) 0);
        return CollectionUtil.toList(indexData);
    }
    private List<IndexData> map2IndexData (List<Map> temp) {
        List<IndexData> datas = new ArrayList<>(16);
        for (Map  m: temp) {
            IndexData indexData = new IndexData();
            String date = m.get("date").toString();
            System.out.println(date);
            float closePoint = Convert.toFloat(m.get("closePoint"));
            indexData.setClosePoint(closePoint);
            indexData.setDate(date);
            datas.add(indexData);
        }
        return datas;
    }



}
